﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;

namespace SignalLab.BaseLibrary
{
  public class PagedArray<T> : IEnumerable<T>
  {
    public int PageSize;

    public PagedArray(int pageSize)
    {
      DataPages = new List<T[]>();
      PageSize = pageSize;
    }

    List<T[]> DataPages;
     
    public void AddPage(T[] data)
    {
      DataPages.Add(data);
    }

    public T[][] GetPages()
    {
      return DataPages.ToArray();
    }


    public T this[int index]
    {
      get
      {
        return DataPages[index / PageSize][index % PageSize];
      }
      set
      {
        this[index] = value;
      }
    }

    public int Count
    {
      get { return PageSize * DataPages.Count; }
    }


    public IEnumerator GetEnumerator()
    {
      return new PagedArrayEnumerator(this);
    }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
      return new PagedArrayEnumerator(this);
    }


    private class PagedArrayEnumerator : IEnumerator<T>
    {
      IEnumerator sourceEnumerator = null;
      IEnumerator currentPageEnumerator;


      public PagedArrayEnumerator(PagedArray<T> source)
      {
        sourceEnumerator = source.GetEnumerator();
      }

      public T Current
      {
        get { return (T)currentPageEnumerator.Current; }
      }

      public void Dispose()
      {
        sourceEnumerator = null;
        currentPageEnumerator = null;
      }

      object IEnumerator.Current
      {
        get { return currentPageEnumerator.Current; }
      }

      public bool MoveNext()
      {
        if (currentPageEnumerator == null || !currentPageEnumerator.MoveNext())
        {
          if (sourceEnumerator.MoveNext())
          {
            currentPageEnumerator = (IEnumerator)sourceEnumerator.Current;
            return currentPageEnumerator.MoveNext();
          }
          else return false;
        }
        return true;
        
      }

      public void Reset()
      {
        sourceEnumerator.Reset();
      }
    }


  }
}
